<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Api\VerifyCodeRequest;
use Illuminate\Http\Request;
use Overtrue\EasySms\EasySms;
use Overtrue\EasySms\Exceptions\NoGatewayAvailableException;

class VerificationCodesController extends Controller
{
    //验证注册接口图片验证码
    public function store(VerifyCodeRequest $request,EasySms $easySms)
    {
        $captchKey=$request->captcha_key;
        $captchCode=$request->captcha_code;
        $captchCache=\Cache::get($captchKey);
        if(!$captchCache){
            return $this->response->error('验证码已过期',422);
        }
        if(!hash_equals($captchCache['code'],$captchCode)){
            //验证错误就清除缓存
            \Cache::forget($captchKey);
            return $this->response->errorUnauthorized('图片验证码不正确');
        }
        $phone=$captchCache['phone'];
        //生成4位随机数,左侧补零
        $code=str_pad(random_int(1,9999),4,0,STR_PAD_LEFT);
        //发送短信
        try{
            $result=$easySms->send($phone,[
                // 'content'=>"【杨晓光】你的验证码是{$code}。如非本人操作请忽略",
                'template' => 'SMS_109340195',
                'data' => [
                    'code' =>$code
                ],
            ]);
        }catch (NoGatewayAvailableException $exception){
            $message=$exception->getException('yunpian')->getMessage();
            return $this->response->errorInternal($message?:'短信发送异常');
        }
        // 缓存相关操作
        $key='verifyCode_'.str_random(15);
        $expiredAt=now()->addMinute(10);
        \Cache::put($key,['phone'=>$phone,'code'=>$code],$expiredAt);
        //返回数据
        return $this->response->array([
           'key'=>$key,
            'expired_at'=>$expiredAt->toDateTimeString()
        ])->setStatusCode(201);
    }
}
